<?php


namespace app\api\controller;


use app\admin\model\Banners;
use app\admin\model\Car;
use app\admin\model\CarOrder;
use app\admin\model\DistinguishLog;
use app\admin\model\Log;
use app\admin\model\Notice;
use app\admin\model\Package;
use app\admin\model\Setting;
use app\admin\model\Station;
use app\admin\model\Store;
use app\api\model\Heatlog;
use app\admin\model\Tag;
use app\Request;
use const http\Client\Curl\Versions\CURL;

class Info
{

    public function getStationInfo(Request $request)
    {
        $stationId = $request->post('station_id');
        $startTime = CarOrder::where('station_id', $stationId)
            ->where('is_pay', 0)
            ->order('id desc')
            ->value('create_time');
        $station = Station::find($stationId);

        return show(config('status.success'), 'success', [
            'name' => $station->name,
            'status' => $station->status,
            'use_time' =>  $station->status == 1 ? get_stay_time(strtotime($startTime ?? 0))  : 0
        ]);
    }

    public function weatherInfo(Request $request)
    {
        $extensions = $request->post('extensions');
        $result = curl("https://restapi.amap.com/v3/weather/weatherInfo?key=682531461bdee926c80ff2c7bf072517&city=140100&extensions={$extensions}");
        return show(config('status.success'), 'success', $result);
    }

    // 轮播图
    public function getBanners()
    {
        $info = DistinguishLog::where('id', 90)->find();
        $list = Banners::order('sort asc')->where(['banner_type'=>0])->field('id,image_path,name')->select();
        return show(config('status.success'), 'success', $list);
    }

    /**
     * 获取附近门店banner图
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBanner(){
        $bannerInfo = Banners::where(['banner_type'=>1,'name'=>'附近门店banner图'])->find();
        return show(config('status.success'), 'success', $bannerInfo);
    }
    /**
     * 获取个人中心banner图
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOwnBanner(){
        $bannerInfo = Banners::where(['banner_type'=>1,'name'=>'个人中心banner图'])->find();
        return show(config('status.success'), 'success', $bannerInfo);
    }

    public function getContents(Request  $request)
    {
        return show(config('status.success'), 'success', Setting::where('key', $request->post('key'))->value('value'));
    }

    public function getStores(Request  $request)
    {
        $lng = input('lng');$lat = input('lat');
        $list = Store::order('sort asc')->withCount(['station'])->order('sort asc')->select();
        foreach ($list as $item) {
            $item->free_count = Station::where(['store_id' => $item->id,'status' => 0])->count();
            //获取门店标签
            $tags = Tag::where(['store_id'=>$item->id])->select();
            $item->tags = !empty($tags)? $tags:[];
            //根据经纬度计算距离
            if(!empty($item->longitude_and_atitude) && !empty($lng) && !empty($lat)){
                list($lng1,$lat1) = explode(',',$item->longitude_and_atitude);
                $item->distance = getDistance($lng,$lat,$lng1,$lat1);
            }else{
                $item->distance =0;
            }
        }
        if(!empty($lng) && !empty($lat) && !empty($list)){
            $list = $list->toArray();
            array_multisort(array_column($list, 'distance'),SORT_ASC,$list);
        }
        return show(config('status.success'), 'success', $list);
    }

    public function getNotice(Request  $request)
    {
        $list = Notice::order('sort asc')->select();
        return show(config('status.success'), 'success', $list);
    }

    public function getStoreDetail(Request  $request)
    {
        $detail = Store::order('sort asc')->field('id,name,banners,address,longitude_and_atitude,manager_id,telephone')
            ->with(['station' => function($query) {
                $query->order('sort desc');
            }])->find($request->post('id'));
        if (empty($detail)) return show(config('status.error'), '门店不存在');
        foreach ($detail['station'] as &$item) {
            $startTime = CarOrder::where('station_id', $item['id'])
                ->where('is_pay', 0)
                ->order('id desc')
                ->value('create_time');

            $item['use_time'] =  $item['status'] == 1 ? get_stay_time(strtotime($startTime ?? 0))  : 0;
        }

        $detail->free_count = Station::where(['store_id' => $detail->id,'status' => 0])->count();
        return show(config('status.success'), 'success', $detail);
    }

    public function getPackage(Request $request)
    {
        $where['store_id'] = $request->post('store_id');
        $where['manager_id'] = $request->post('manager_id');
        $detail = Package::order('sort asc')->where($where)->select();
        return show(config('status.success'), 'success', $detail);
    }

    public function recHeartbeat(Request $request)
    {
        $post = $request->post();
        if (!empty($post)) {
            $a = $OBJ = Heatlog::create([
                'content' => $post
            ]);
            $count = Heatlog::count('id');
            $delCount = 300;
            if ($count > $delCount) {
                $id = Heatlog::order('id desc')->value('id');
                Heatlog::where('id', '<', $id - $delCount)->delete();
            }

            $station = Station::where([
                'serialno' => $post['serialno'] ?? ''
            ])->find();
            if (!empty($station)) {
                if ($station->status == 1) {
                    // 正在洗车
                    // $data = 'qlUQgNUACkIl1f3U2s+0s7VFoa8=';

                    $data = 'qlUCgNUABkIl1f3U2lEjrw==';
                    $responseData = [
                        'Response_AlarmInfoPlate' => [
                            'serialData' => [
                                ['serialChannel' => 0,'data' =>$data, 'dataLen' => 20]
                            ]
                        ]
                    ];
                } else {
                    // 空闲中
                    // $data = 'qlUMgNUACEIlv9XP0NbQ1kKv';
                   $data = 'qlUBgNUABkIlv9XP0IEurw==';
                    $responseData = [
                        'Response_AlarmInfoPlate' => [
                            'serialData' => [
                                ['serialChannel' => 0,'data' =>$data, 'dataLen' => 18]
                            ]
                        ]
                    ];
                }

                return json($responseData);
            }


        }

    }

    // 获取车牌识别结果
    public function getCarDistinguishResult(Request $request)
    {
        $data = file_get_contents("php://input");
        if (empty($data)) return '非法请求';

        $fp = fopen(root_path() . "/snap_shot.txt", "a+");
        if(!$fp){
            return '';
        }
        $flag=fwrite($fp, $data);
//$flag=fwrite($fp, $jsondecode['AlarmInfoPlate']['result']['PlateResult']['imagePath']);
        if(!$flag)
        {
            fclose($fp);
            return '';
        }

        fclose($fp);
//        $data = $request->post();
        $data = \Qiniu\json_decode($data, true);
        $logData = [
            'content' => $data,
        ];
        $responseData = [
            'Response_AlarmInfoPlate' => [
                'info' => 'NO'
            ]
        ];
        $carId = $data['AlarmInfoPlate']['result']['PlateResult']['license'] ?? false;
        if (empty($carId)) {
            $logData['remark'] = '未识别到车牌号';
            DistinguishLog::create($logData);
            return json($responseData);
        }

        // 设备序列号
        $serialno = $data['AlarmInfoPlate']['serialno'] ?? false;
        if (empty($serialno)) {
            $logData['remark'] = '未识别到设备序列号';
            DistinguishLog::create($logData);
            return json($responseData);
        }

        // 查找工位
        $station = Station::where('serialno', $serialno)
            ->findOrEmpty();

        if ($station->isEmpty()) {
            $logData['remark'] = '未匹配到工位';
            DistinguishLog::create($logData);
            return json($responseData);
        }

        // 查看是否空闲中
        if ($station->status == 1) {
            $logData['station_id'] = $station->id;
            $logData['remark'] = '该工位已有人在洗车';
            DistinguishLog::create($logData);
            return json($responseData);
        }

        if (CarOrder::where('license', $carId)->where('create_time','>', date('Y-m-d'))
                ->where('create_time','<=', date('Y-m-d') . ' 23:59:59')->count() > 0) {
            $logData['station_id'] = $station->id;
            $logData['remark'] = $carId . ',该车牌今日已识别过，此次操作不会再打开门';
            DistinguishLog::create($logData);
            return json($responseData);
        }

        // 查找门店
        $store = Store::findOrEmpty($station->store_id);
        if ($store->isEmpty()) {
            $logData['station_id'] = $station->id;
            $logData['remark'] = '未匹配到门店';
            DistinguishLog::create($logData);
            return json($responseData);
        }

        // 匹配车辆
        $cars = Car::where('license_plate', $carId)->select();
        if ($cars->isEmpty()) {
            $logData['station_id'] = $station->id;
            $logData['remark'] = '该车牌未被用户绑定';
            DistinguishLog::create($logData);
            return json($responseData);
        }

        // 找车主
        $targetUser = null;
        $targetCar = null;
        foreach ($cars as $car) {
            $user = \app\admin\model\User::findOrEmpty($car->user_id);
            if (!$user->isEmpty()) {
//                if ($user->price >= $store->start_price) {
                    $targetUser = $user;
                    $targetCar  = $car;
                    break;
//                }
            }
        }

        if (empty($targetUser)) {
            $logData['station_id'] = $station->id;
            $logData['remark'] = '未匹配到适合的用户';
            DistinguishLog::create($logData);
            return json($responseData);
        }
        if ($targetUser->price <= 0) {
            $logData['station_id'] = $station->id;
            $logData['user_id'] = $targetCar->id;
            $logData['remark'] = '余额不足';
            DistinguishLog::create($logData);
            return json($responseData);
        }


        // 开门
        $doorObj = new \app\api\controller\User(app());
        $doorObj->operateDoor(1, $targetUser->id, $station->id, $station->dev_id, 1, 1, $targetCar->id);
        if ($doorObj->isSuccessByDoor === false) {
            $logData['remark'] = '开门失败';
            $logData['station_id'] = $station->id;
            $logData['user_id'] = $targetUser->id;
            $logData['car_id'] = $targetCar->id;
            $logData['is_preg_user'] = 1;
            DistinguishLog::create($logData);
            return json($responseData);
        } else {
            $logData['is_preg_user'] = 1;
            $logData['user_id']      = $targetUser->id;
            $logData['car_id']       = $targetCar->id;
            $logData['is_open_door'] = 1;
            DistinguishLog::create($logData);
            $responseData = [
                'Response_AlarmInfoPlate' => [
                    'info' => 'ok'
                ]
            ];
            return json($responseData);
        }
    }

    public function getStations(Request  $request)
    {
        $list = Station::where('store_id', 2)->field('id,name,status')->select();
        $store = Store::find(2);

        return show(config('status.success'), 'success', [
            'name' => $store->name,
            'list' => $list
        ]);
    }

    public function operatorDoor(Request  $request)
    {
        $obj = Station::find($request->post('id'));
        if (empty($obj)) return show(config('status.error'), '工位不存在');
        $statObj = new \app\admin\controller\Station(app());
        return $statObj->operateDoor($request);
    }

    /**
     * 根据商户id查询门店列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
        public function getStoreList(Request  $request){
        $manager_id = $request->post('manager_id');
        if(empty($manager_id)){
            return show(config('status.error'), '商户id不允许为空');
        }
        $list = Store::where(['manager_id'=>$manager_id])->order('sort asc')->withCount(['station'])->order('sort asc')->select();
        foreach ($list as $item) {
            $item->free_count = Station::where(['store_id' => $item->id,'status' => 0])->count();
            //获取门店标签
            $tags = Tag::where(['store_id'=>$item->id])->select();
            $item->tags = !empty($tags)? $tags:[];
        }
        return show(config('status.success'), 'success', $list);
    }
}